package com.starry.module.system.core.checkcode.service.impl;

import com.starry.module.system.api.checkcode.domain.qo.CaptchaCreateQo;
import com.starry.module.system.api.checkcode.domain.vo.CaptchaVo;
import com.starry.module.system.core.checkcode.properties.CaptchaProperties;
import com.starry.module.system.core.checkcode.service.CaptchaStrategy;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.IOException;
import java.util.UUID;

/**
 * @Description 字符验证码
 * @Author xiaoke
 */
@Service("spec_captcha")
public class SpecCaptchaStrategy implements CaptchaStrategy {
    private final CaptchaProperties captchaProperties;

    public SpecCaptchaStrategy(CaptchaProperties captchaProperties) {
        this.captchaProperties = captchaProperties;
    }

    @Override
    public CaptchaVo generateCaptcha(CaptchaCreateQo dto) {
        //生成验证码对象
        SpecCaptcha captcha = new SpecCaptcha(
                captchaProperties.getWidth(),
                captchaProperties.getHeight(),
                captchaProperties.getLen());
        try {
            captcha.setFont(Captcha.FONT_1); // 设置系统字体
        } catch (IOException | FontFormatException e) {
            return null;
        }
        captcha.setFont(new Font("楷体", Font.PLAIN, 28));
        return CaptchaVo.builder()
                .img(captcha.toBase64())
                .result(captcha.text().toLowerCase())
                .key(UUID.randomUUID().toString())
                .build();
    }
}
